package com.fengxu.netty.tcp.protocol;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.UUID;

// tcp服务器粘包测试
public class MyServer {

    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new MyMessageEncoder());
                        pipeline.addLast(new MyMessageDecoder());
                        pipeline.addLast(new MyServerHandler());
                    }
                });
        ChannelFuture channelFuture = serverBootstrap.bind(6666).sync();
        channelFuture.addListener(future -> {
            if(future.isSuccess()){
                System.out.println("绑定端口成功");
            } else {
                System.out.println("绑定端口失败!");
            }
        });
        channelFuture.channel().closeFuture().sync();
    }


    // 自定义服务器处理器
    private static class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol>{

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
            System.out.println("服务器读取到数据:"+msg);
            String resp = UUID.randomUUID().toString();
            byte[] bytes = resp.getBytes("utf-8");

            // 返回给客户端消息
            ctx.writeAndFlush(new MessageProtocol().setLen(bytes.length).setContent(bytes));
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("异常信息:"+cause.getMessage());
            ctx.close();
        }
    }

}


